package com.example.esp8266.Equipment.Task_Fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.room.Room;

import com.example.esp8266.Init.ESP8266_APP;
import com.example.esp8266.Library.RoomLib.AppDatabase;
import com.example.esp8266.Library.RoomLib.Task;
import com.example.esp8266.Library.RoomLib.TaskDetail;
import com.example.esp8266.R;

import com.example.esp8266.Library.RoomLib.Dao_Interface.TaskDao;
import com.example.esp8266.Library.RoomLib.Dao_Interface.TaskDetailDao;


public class TaskCreate extends Fragment {
    private String back_info,task_group_name_bundle;
    private View root;
    private int taskGroupId;

    private Spinner spinnerDevice, spinnerSensor;
    private RadioGroup radioGroup;
    private RadioButton radioButtonStart, radioButtonStop;
    private CheckBox checkboxDelayStart;
    private EditText edittextDelayParameter, sensorLowerParameterLimit, sensorParameterUpperLimit;
    private Button buttonConfirmTask, buttonRenameTask, buttonCancelTask;

    private String command_target, command_status, criteria, delay ,sensor_target;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 获取传递的数据
        Bundle args = getArguments();
        if (args != null) {
            back_info = args.getString("back_info", ""); // 返回上一层标识
            taskGroupId = args.getInt("task_groupId", -1); // 获取任务组ID
            task_group_name_bundle = args.getString("task_groupName", null); // 获取任务组名字
        }
        // 检查 getActivity() 是否返回的对象为非空
        if (getActivity() != null) {
            // 获取 SharedPreferences 对象
            SharedPreferences sharedPreferences = getActivity().getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("previous_page", back_info);
            editor.apply();
        } else {
            Log.e("TaskCreate", "getActivity() returned null");
            // 可以选择在这里处理 getActivity() 返回 null 的情况，例如显示错误信息或采取其他操作
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        root = inflater.inflate(R.layout.task_create_fragment, container, false);

        // 初始化界面元素
        spinnerDevice = root.findViewById(R.id.spinner_device);
        spinnerSensor = root.findViewById(R.id.spinner_sensor);

        // 设置继电器选项选择监听器
        spinnerDevice.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // 获取选中的项
                String selectedItem = (String) parent.getItemAtPosition(position);
                // 执行不同操作
                switch (position) {
                    case 0:
                        // 用户选择了 Option 1
                        Toast.makeText(getActivity(), "Selected: " + selectedItem, Toast.LENGTH_SHORT).show();
                        command_target = "CTRL.Relay1";
                        // 执行 Option 1 的相关操作
                        break;
                    case 1:
                        // 用户选择了 Option 2
                        Toast.makeText(getActivity(), "Selected: " + selectedItem, Toast.LENGTH_SHORT).show();
                        // 执行 Option 2 的相关操作
                        command_target = "CTRL.Relay2";
                        break;
                    case 2:
                        // 用户选择了 Option 3
                        Toast.makeText(getActivity(), "Selected: " + selectedItem, Toast.LENGTH_SHORT).show();
                        // 执行 Option 3 的相关操作
                        command_target = "CTRL.Relay3";
                        break;
                    case 3:
                        // 用户选择了 Option 4
                        Toast.makeText(getActivity(), "Selected: " + selectedItem, Toast.LENGTH_SHORT).show();
                        // 执行 Option 4 的相关操作
                        command_target = "CTRL.Relay4";
                        break;
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // 当没有选中任何选项时的操作（可以留空）
            }
        });

        // 设置传感器选项选择监听器
        spinnerSensor.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // 获取选中的项
                String selectedItem = (String) parent.getItemAtPosition(position);
                // 执行不同操作
                switch (position) {
                    case 0:
                        // 用户选择了 Option 1
                        Toast.makeText(getActivity(), "Criteria: " + selectedItem, Toast.LENGTH_SHORT).show();
                        sensor_target = "Tem";
                        // 执行 Option 1 的相关操作
                        break;
                    case 1:
                        // 用户选择了 Option 2
                        Toast.makeText(getActivity(), "Criteria: " + selectedItem, Toast.LENGTH_SHORT).show();
                        // 执行 Option 2 的相关操作
                        sensor_target = "Hum";
                        break;
                    case 2:
                        // 用户选择了 Option 3
                        Toast.makeText(getActivity(), "Criteria: " + selectedItem, Toast.LENGTH_SHORT).show();
                        // 执行 Option 3 的相关操作
                        sensor_target = "CO2";
                        break;
                    case 3:
                        // 用户选择了 Option 4
                        Toast.makeText(getActivity(), "Criteria: " + selectedItem, Toast.LENGTH_SHORT).show();
                        // 执行 Option 4 的相关操作
                        sensor_target = "PM25";
                        break;
                    case 4:
                        // 用户选择了 Option 5
                        Toast.makeText(getActivity(), "Criteria: " + selectedItem, Toast.LENGTH_SHORT).show();
                        // 执行 Option 5 的相关操作
                        sensor_target = "LUX";
                        break;
                    case 5:
                        // 用户选择了 Option 6
                        Toast.makeText(getActivity(), "Criteria: " + selectedItem, Toast.LENGTH_SHORT).show();
                        // 执行 Option 6 的相关操作
                        sensor_target = "REL";
                        break;
                    case 6:
                        // 用户选择了 Option 7
                        Toast.makeText(getActivity(), "Criteria: " + selectedItem, Toast.LENGTH_SHORT).show();
                        // 执行 Option 7 的相关操作
                        sensor_target = "None";
                        break;
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // 当没有选中任何选项时的操作（可以留空）
            }
        });

        radioGroup = root.findViewById(R.id.radioGroup);
        radioButtonStart = root.findViewById(R.id.radiobutton_start);
        radioButtonStop = root.findViewById(R.id.radiobutton_stop);

        checkboxDelayStart = root.findViewById(R.id.checkbox_delay_start);
        edittextDelayParameter = root.findViewById(R.id.edittext_delay_parameter);

        sensorLowerParameterLimit = root.findViewById(R.id.sensor_lower_parameter_limit);
        sensorParameterUpperLimit = root.findViewById(R.id.sensor_parameter_upper_limit);

        buttonConfirmTask = root.findViewById(R.id.button_confirm_task);
        buttonRenameTask = root.findViewById(R.id.button_rename_task);
        buttonCancelTask = root.findViewById(R.id.button_cancel_task);
        buttonConfirmTask.setOnClickListener(v -> validateAndCreateTask());
        buttonCancelTask.setOnClickListener(v -> cancel_create());

        return root;
    }

    private void cancel_create(){
        Toast.makeText(getActivity(), "取消创建任务", Toast.LENGTH_SHORT).show();
        Bundle args = new Bundle();
        args.putString("back_info", "TaskRun_Fragment");
        args.putString("task_groupName", task_group_name_bundle); // 传递任务组名称
        args.putInt("task_groupId", taskGroupId); // 传递任务组ID

        // 处理点击事件，切换到 TaskList_Fragment 并传递任务组ID
        TaskList_Fragment taskListFragment = new TaskList_Fragment();
        taskListFragment.setArguments(args);
        replaceFragment(taskListFragment);
    }

    private void validateAndCreateTask() {
        // 检查是否选择了启动或停止
        int selectedRadioId = radioGroup.getCheckedRadioButtonId();
        if (selectedRadioId == -1) {
            Toast.makeText(getActivity(), "请选择启动或停止选项", Toast.LENGTH_SHORT).show();
            return;
        }


        if (selectedRadioId == R.id.radiobutton_start) {
            command_status = "(True)";
        } else if (selectedRadioId == R.id.radiobutton_stop) {
            command_status = "(False)";
        } else {
            command_status = "";
        }

        // 检查延迟触发选项
        if (checkboxDelayStart.isChecked()) {
            String delayText = edittextDelayParameter.getText().toString().trim();
            if (TextUtils.isEmpty(delayText) || !TextUtils.isDigitsOnly(delayText) || Integer.parseInt(delayText) <= 0) {
                Toast.makeText(getActivity(), "请输入有效的延迟时间", Toast.LENGTH_SHORT).show();
                return;
            }
            delay = delayText;
        } else {
            delay = null;
        }

        // 检查传感器参数阈值
        String lowerLimitText = sensorLowerParameterLimit.getText().toString().trim();
        String upperLimitText = sensorParameterUpperLimit.getText().toString().trim();
        if (TextUtils.isEmpty(lowerLimitText) || TextUtils.isEmpty(upperLimitText) ||
                !TextUtils.isDigitsOnly(lowerLimitText) || !TextUtils.isDigitsOnly(upperLimitText) ||
                Integer.parseInt(lowerLimitText) > Integer.parseInt(upperLimitText)) {
            Toast.makeText(getActivity(), "请输入有效的传感器阈值（下限不能大于上限）", Toast.LENGTH_SHORT).show();
            return;
        }

        criteria = sensor_target + "_L" + lowerLimitText + "_H" + upperLimitText;
        if (sensor_target.contains("REL") || sensor_target.contains("None"))
        {
            criteria = sensor_target;
        }
        showCreateTaskGroupDialog();
    }

    /**新建任务的重命名对话框*/
    private void showCreateTaskGroupDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        builder.setTitle("新建任务");

        // 设置对话框的输入框
        final EditText input = new EditText(getContext());
        builder.setView(input);

        // 设置 "取消" 按钮
        builder.setNegativeButton("取消", (dialog, which) -> dialog.cancel());

        // 设置 "确认" 按钮
        builder.setPositiveButton("确认", (dialog, which) -> {
            String New_taskName = input.getText().toString();
            if (TextUtils.isEmpty(New_taskName)) {
                New_taskName = "Task " + System.currentTimeMillis();
            }
            createNewTask(New_taskName);
        });

        builder.show();
    }

    /**新建任务逻辑*/
    @SuppressLint("NotifyDataSetChanged")
    private void createNewTask(String taskName) {
        // 创建一个 Task 对象
        Task task = new Task(taskGroupId, taskName); // 这里 Task 名称包含时间戳，确保唯一性
        new Thread(() -> {
            AppDatabase database = ESP8266_APP.getInstance().getDatabase();
            TaskDao taskDao = database.taskDao();

            // 插入 Task 并获取其 ID
            long taskId = taskDao.insert(task);

            // 创建 TaskDetail 并插入到数据库
            TaskDetail taskDetail = new TaskDetail((int) taskId, command_target+command_status, criteria, delay != null ? Integer.parseInt(delay) : 0);
            TaskDetailDao taskDetailDao = database.taskDetailDao();
            taskDetailDao.insert(taskDetail);

            // 在主线程显示 Toast 消息
            requireActivity().runOnUiThread(() -> {
                Toast.makeText(getActivity(), "任务创建成功", Toast.LENGTH_SHORT).show();
                Bundle args = new Bundle();
                args.putString("back_info", "TaskRun_Fragment");
                args.putString("task_groupName", task_group_name_bundle); // 传递任务组名称
                args.putInt("task_groupId", taskGroupId); // 传递任务组ID

                // 处理点击事件，切换到 TaskList_Fragment 并传递任务组ID
                TaskList_Fragment taskListFragment = new TaskList_Fragment();
                taskListFragment.setArguments(args);
                replaceFragment(taskListFragment);
            });
        }).start();
    }

    /** 动态切换视图*/
    private void replaceFragment(Fragment fragment) {
        if (getActivity() != null) {
            FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            transaction.replace(R.id.control_fragment_view, fragment);
            transaction.commit();
        }
    }
}